﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.IO;
using System.Linq;

namespace ControlCenterService.WebApi
{
    internal static class SwaggerExtensions
    {
        /// <summary>
        ///  Register the Swagger generator, defining one or more Swagger documents
        /// </summary>
        public static IServiceCollection AddSwagger(this IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "ControlCenterService API",
                    Description = "",
                    TermsOfService = "None"
                });

               
                c.DocumentFilter<LowercaseDocumentFilter>();

                //Set the comments path for the swagger json and ui.
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "ControlCenterService.WebApi.xml"));
                // dto 所在类库的 xml 文档
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "ControlCenter.ApplicationService.xml"));
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "ControlCenter.Model.xml"));
                c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "ControlCenter.Operation.xml"));
            });

            return services;
        }

        public static IApplicationBuilder UseSwagger(this IApplicationBuilder app)
        {
            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(c => c.RouteTemplate = "api/{documentName}/controlcenterService/swagger.json");

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/api/v1/controlcenterService/swagger.json", "RPA 控制中心 WebApi API V1");
                c.RoutePrefix = "api/v1/controlcenterService/swagger";

            });

            return app;
        }
    }

    internal class LowercaseDocumentFilter : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Paths = swaggerDoc.Paths.ToDictionary(k => LowercasePath(k.Key), v => v.Value);

            string LowercasePath(string path)
            {
                var separatedPaths = path.Split('/');

                for (var i = 0; i < separatedPaths.Length; i++)
                {
                    if (!(separatedPaths[i].StartsWith('{') && separatedPaths[i].EndsWith('}')))
                    {
                        separatedPaths[i] = separatedPaths[i].ToLower();
                    }
                }

                return string.Join('/', separatedPaths);
            }
        }
    }
}
